﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Security.Cryptography;
using System.IO;
using System.Web.UI;
using System.Data;
using Telerik.Web.UI;
using System.Text;
using System.Web.UI.WebControls;

namespace SRM
{


    /// <summary>
    /// Summary description for Helpers
    /// </summary>
    public class Helpers
    {
        public Helpers()
        {
            //
            // TODO: Add constructor logic here
            //
        }
    }

    public class Help
    {
        public static void SendEmail(string emailAddress, string emailSubject, string emailBody, bool isBodyHtml)
        {
            string SmtpServer = System.Configuration.ConfigurationManager.AppSettings["Smtp_Server"];
            string SenderEmail = System.Configuration.ConfigurationManager.AppSettings["Sender_Email"];
            string SenderName = System.Configuration.ConfigurationManager.AppSettings["Sender_Name"];
            string EmailQueuePath = System.Configuration.ConfigurationManager.AppSettings["Email_Queue_Path"];
            string DeveloperEmail = System.Configuration.ConfigurationManager.AppSettings["Developer_Email"];
            string DeveloperName = System.Configuration.ConfigurationManager.AppSettings["Developer_Name"];

            const string Email_CharSet = "UTF-8";

            ASPEMAILLib.IMailSender mailMessage = new ASPEMAILLib.MailSender();
            mailMessage = new ASPEMAILLib.MailSender();
            mailMessage.Host = SmtpServer;
            mailMessage.From = SenderEmail;
            mailMessage.FromName = mailMessage.EncodeHeader(SenderName, Email_CharSet);

            mailMessage.CharSet = Email_CharSet;
            mailMessage.ContentTransferEncoding = "Quoted-Printable";
            mailMessage.Subject = mailMessage.EncodeHeader(emailSubject, Email_CharSet);

            mailMessage.AddAddress(emailAddress, Type.Missing);

            mailMessage.Body = emailBody;
            mailMessage.IsHTML = isBodyHtml ? 1 : 0;
            mailMessage.Queue = 1;
            mailMessage.Send(EmailQueuePath);
        }

        public static void SendExceptionAlertEmail(string body)
        {
            string SmtpServer = System.Configuration.ConfigurationManager.AppSettings["Smtp_Server"];
            string SenderEmail = System.Configuration.ConfigurationManager.AppSettings["Sender_Email"];
            string SenderName = System.Configuration.ConfigurationManager.AppSettings["Sender_Name"];
            string EmailQueuePath = System.Configuration.ConfigurationManager.AppSettings["Email_Queue_Path"];
            string DeveloperEmail = System.Configuration.ConfigurationManager.AppSettings["Developer_Email"];
            string DeveloperName = System.Configuration.ConfigurationManager.AppSettings["Developer_Name"];

            // TODO: Refactor the hard-coded bits to be read from configuration settings instead.
            System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(SmtpServer);
            System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage();
            mailMessage.From = new System.Net.Mail.MailAddress(SenderEmail, SenderName);
            mailMessage.To.Add(new System.Net.Mail.MailAddress(DeveloperEmail, DeveloperName));
            mailMessage.Subject = "An exception has occurred on SRM.";
            mailMessage.SubjectEncoding = System.Text.Encoding.UTF8;
            mailMessage.Body = body;
            mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
            mailMessage.IsBodyHtml = false;
            smtpClient.Send(mailMessage);

            //SendEmail(DeveloperEmail, "test", body, false);
        }

        public static string GetConnectionString(string name)
        {
            if (ConfigurationManager.ConnectionStrings[name] != null)
                return ConfigurationManager.ConnectionStrings[name].ConnectionString;

            return string.Empty;
        }

        public static string Incr(string intStr)
        {
            int result;
            if (int.TryParse(intStr, out result))
                result++;
            return result.ToString();
        }
        public static string Decr(string intStr)
        {
            int result;
            if (int.TryParse(intStr, out result))
                result--;
            return result.ToString();
        }

        

        public static string GetAppSetting(string settingName)
        {
            return ConfigurationManager.AppSettings[settingName];
        }

        public static string Decrypt(string val)
        {
            string result = string.Empty;
            const string DESKey = "AQWSEDRF";
            const string DESIV = "HGFEDCBA";

            byte[] key = null;
            byte[] iv = null;
            byte[] inputByteArray = null;

            key = System.Text.Encoding.UTF8.GetBytes(DESKey);
            iv = System.Text.Encoding.UTF8.GetBytes(DESIV);

            inputByteArray = Convert.FromBase64String("KeSl3TfM/OLUHgGD+4+aJ/g7wYBdoZXrEtqRp0Esz8u+S/c55K1VcQ==");

            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, iv), CryptoStreamMode.Write);

            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();

            result = System.Text.Encoding.UTF8.GetString(ms.ToArray());

            //return string.Empty;
            return string.Empty;
        }
        
        //Private Shared Function Convert2ByteArray(ByVal strInput As String) As Byte()
        //    Dim intCounter As Integer
        //    Dim arrChar As Char()
        //    arrChar = strInput.ToCharArray()
        //    Dim arrByte As Byte() = New Byte(arrChar.Length - 1) {}
        //    For intCounter = 0 To arrByte.Length - 1
        //        arrByte(intCounter) = Convert.ToByte(arrChar(intCounter))
        //    Next
        //    Return arrByte
        //End Function

        public static byte[] ConvertToByteArray(string input)
        {
            int counter;
            char[] characters;
            byte[] result = null;

            characters = input.ToCharArray();
            result = new byte[characters.Length];
            for (counter = 0; counter < result.Length; counter++)
            {
                result[counter] = Convert.ToByte(characters[counter]);
            }

            return result;
        }

        public static string GetRadComboBoxValue(Control c)
        {
            Telerik.Web.UI.RadComboBox rc = c as Telerik.Web.UI.RadComboBox;
            if (rc == null)
                return string.Empty;
            else
                return rc.SelectedValue;
        }

        public static string GetRadDatePickerValue(Control c)
        {
            Telerik.Web.UI.RadDatePicker rc = c as Telerik.Web.UI.RadDatePicker;
            if ((rc == null) || (rc.SelectedDate == null))
                return string.Empty;
            else
                return rc.SelectedDate.Value.ToString("yyyy-MM-dd");
        }

        public static string GetRadNumericTextBoxValue(Control c)
        {
            Telerik.Web.UI.RadNumericTextBox rc = c as Telerik.Web.UI.RadNumericTextBox;
            if ((rc == null) || (rc.Value == null))
                return string.Empty;
            else
                return rc.Value.Value.ToString();
        }

        public static string GetHiddenFieldValue(Control c)
        {
            System.Web.UI.WebControls.HiddenField rc = c as System.Web.UI.WebControls.HiddenField;
            if (rc == null)
                return string.Empty;
            else
                return rc.Value;
        }

        public static string GetTextBoxValue(Control c)
        {
            System.Web.UI.WebControls.TextBox rc = c as System.Web.UI.WebControls.TextBox;
            if (rc == null)
                return string.Empty;
            else
                return rc.Text.Trim();
        }

        public static string GetRadioButtonListValue(Control c)
        {
            System.Web.UI.WebControls.RadioButtonList rc = c as System.Web.UI.WebControls.RadioButtonList;
            if (rc == null)
                return string.Empty;
            else
                return rc.SelectedValue;
        }

        public static object GetValueOrDBNull(object o)
        {
            if (o == null)
                return DBNull.Value;

            return o;
        }

        public static object GetValueOrDBNullForNumber(object o)
        {
            if (o == null)
                return DBNull.Value;

            if (o is string)
            {
                if (string.IsNullOrEmpty(o.ToString()))
                    return DBNull.Value;
            }
                

            return o;
        }

        public static void BindSrmCodeToComboBox(Telerik.Web.UI.RadComboBox comboBox, DataTable dt)
        {
            comboBox.Items.Clear();
            comboBox.Items.Add(new RadComboBoxItem("Please select", string.Empty));
            comboBox.Text = "";
            foreach (DataRow dr in dt.Rows)
            {
                comboBox.Items.Add(new RadComboBoxItem(dr["Description"].ToString(), dr["CodeName"].ToString()));
            }
        }

        public static void BindSapCodeToComboBox(Telerik.Web.UI.RadComboBox comboBox, DataTable dt)
        {
            comboBox.Items.Clear();
            comboBox.Items.Add(new RadComboBoxItem("Please select", string.Empty));
            comboBox.Text = "";
            foreach (DataRow dr in dt.Rows)
            {
                comboBox.Items.Add(new RadComboBoxItem(dr["DisplayText"].ToString(), dr["Id"].ToString()));
            }
        }

        public static Control FindControlRecursive(ControlCollection cc, string id)
        {
            Control foundControl = null;

            foreach (Control c in cc)
            {
                if ((c.ID != null) && (c.ID.Equals(id)))
                {
                    foundControl = c;
                    break;
                }

                if (c.HasControls())
                {
                    foundControl = FindControlRecursive(c.Controls, id);
                    if (foundControl != null)
                        break;
                }
            }

            return foundControl;
        }

        public static double? GetNullableDouble(string str)
        {
            double? result = null;
            double temp;

            if (str == null)
                return result;

            if (double.TryParse(str, out temp))
            {
                result = temp;
            }

            return result;
        }

        //Shared Function GenerateHash(ByVal SourceTStext As String) As String
        //    'Create an encoding object to ensure the encoding standard for the source text
        //    Dim Ue As New UnicodeEncoding()
        //    'Retrieve a byte array based on the source text
        //    Dim ByteSourceText() As Byte = Ue.GetBytes(SourceTStext)
        //    'Instantiate an MD5 Provider object
        //    Dim Md5 As New MD5CryptoServiceProvider()
        //    'Compute the hash value from the source
        //    Dim ByteHash() As Byte = Md5.ComputeHash(ByteSourceText)
        //    'And convert it to String format for return
        //    Return Convert.ToBase64String(ByteHash)
        //End Function

        public static string ComputeMD5(string input)
        {
            byte[] plainTextBytes = Encoding.Unicode.GetBytes(input);
            MD5 md5 = MD5CryptoServiceProvider.Create();
            byte[] cipherTextBytes = md5.ComputeHash(plainTextBytes);
            return Convert.ToBase64String(cipherTextBytes);
        }

        public static string GenerateNewPassword()
        {
            string passwordCharacters = "abcdefghijklmnopqrstuvwxyz0123456789";
            int passwordLength = 12;
            StringBuilder pwd = new StringBuilder(passwordLength);
            Random r = new Random();

            for (int i = 0; i < passwordLength; i++)
            {
                pwd.Append(passwordCharacters[r.Next(0, passwordCharacters.Length - 1)]);
            }
                
            return pwd.ToString();
        }

        public static string GetListItemValue(ListItemCollection col, string val)
        {
            ListItem result = null;

            result = col.FindByValue(val);

            if (result != null)
                return result.Value;

            return null;
            
        }

        public static void SetComboBoxSelectedValue(RadComboBox comboBox, string val)
        {
            RadComboBoxItem foundItem = comboBox.Items.FindItemByValue(val, true);
            if (foundItem != null)
                comboBox.SelectedValue = foundItem.Value;
        }

        public static string HelloWorld()
        {
            return "hello world";
        }
    }
}